package com.example.Project.user;

import com.example.Project.Class.MassOrganizations;
import com.example.Project.user.userHttpMethods.userMethods;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Optional;


public class HelloController {
    void start() throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("hello-view.fxml"));
        Scene scene = new Scene((Parent)fxmlLoader.load(), 811.0, 517.0);
        Stage stage=new Stage();
        stage.setTitle("社团信息管理");
        stage.setScene(scene);
        stage.setResizable(false);
        stage.show();
    }
    com.example.Project.user.userHttpMethods.userMethods userMethods=new userMethods();
    private int page=1;
    private int totalPage=1;

    @FXML
    private TextField ID;
    @FXML
    private Pagination Page;
    @FXML
    private AnchorPane Pane;
    @FXML
    private Button add;
    @FXML
    private RadioButton aihao;
    @FXML
    private DatePicker birthday;
    @FXML
    private ContextMenu menu;
    @FXML
    private Button modify;
    @FXML
    private RadioButton gongneng;
    @FXML
    private RadioButton yishu;
    @FXML
    private TextField name;
    @FXML
    private TextField phone;
    @FXML
    private Button query;
    @FXML
    private TableView<MassOrganizations> table;
    @FXML
    private TableColumn<MassOrganizations, Integer> tableId;
    @FXML
    private TableColumn<MassOrganizations, String> tableName;
    @FXML
    private TableColumn<MassOrganizations, Date> tableBirthday;
    @FXML
    private TableColumn<MassOrganizations, String> tableType;
    @FXML
    private TableColumn<MassOrganizations, String> tablePhone;
    @FXML
    private ToggleGroup type;
    @FXML
    private void btnDel(ActionEvent actionEvent) throws IOException {
        int deleteId=table.getSelectionModel().getSelectedItem().getId();
        String name=table.getSelectionModel().getSelectedItem().getName();
        System.out.println(deleteId);
        //使用系统确认框询问
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setHeaderText("您确定要解散此社团吗？");
        // 显示对话框，并等待按钮返回
        Optional<ButtonType> result = alert.showAndWait();
        // 判断返回的按钮类型是确定还是取消，再据此分别进一步处理
        if (result.get() == ButtonType.OK) { // 单击确定按钮OK
            boolean re=userMethods.deleteMassOrganization(deleteId);
            System.out.println(re);
            Alert al = new Alert(Alert.AlertType.CONFIRMATION);
            if(re==true){
                al.setHeaderText("'"+name+"'社团已解散！");
            }else {
                al.setHeaderText("社团删除失败，请尝试重新进行操作！！！");
            }
            al.showAndWait();
        }
        newTable();
    }

    //编辑状态下解锁可以修改信息
    @FXML
    private void btnAlt(ActionEvent actionEvent) throws IOException, ClassNotFoundException {
        modify.setDisable(false);
        name.setEditable(true);
        phone.setEditable(true);
        birthday.setEditable(true);
        gongneng.setDisable(false);
        aihao.setDisable(false);
        yishu.setDisable(false);
    }
    @FXML
    public void btnLookUser(ActionEvent actionEvent) throws IOException {
        ShowMassUserController enter=new ShowMassUserController();
        enter.get(table.getSelectionModel().getSelectedItem().getId());
        enter.start();
    }
    @FXML
    public void initialize() throws ClassNotFoundException, IOException {
        getPage();
        table.setRowFactory(tv -> {
            TableRow<MassOrganizations> row = new TableRow<>();
            row.setOnMouseClicked(event -> {
                if (!row.isEmpty() && event.getButton() == MouseButton.PRIMARY) {
                    MassOrganizations rowData = row.getItem();
                    System.out.println("Clicked on: " + rowData.getId());
                    ID.setEditable(false);
                    ID.setText(String.valueOf(rowData.getId()));
                    name.setEditable(false);
                    name.setText(rowData.getName());
                    phone.setEditable(false);
                    phone.setText(rowData.getPhone());
                    birthday.setEditable(false);
                    birthday.setValue(rowData.getBirthday());
                    String type = rowData.getType();
                    if (type.equals("功能型")) {
                        gongneng.setSelected(true);
                    } else if (type.equals("爱好型")) {
                        aihao.setSelected(true);
                    } else if (type.equals("艺术型")) {
                        yishu.setSelected(true);
                    }
                    gongneng.setDisable(true);
                    aihao.setDisable(true);
                    yishu.setDisable(true);
                }
            });
            return row;
        });
        modify.setDisable(true);
        table.getItems().clear();
        ObservableList<MassOrganizations> massOrganizationsList= userMethods.getMassOrganization(page);
        System.out.println(massOrganizationsList);
        Platform.runLater(() -> updateTableView(massOrganizationsList));
    }


    @FXML
    void addMass(MouseEvent event) throws IOException {
        Stage Query = new Stage();
        FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("addMass.fxml"));
        Scene scene = new Scene((Parent)fxmlLoader.load(), 320.0, 373.0);
        Query.setTitle("新建社团");
        Query.setScene(scene);
        Query.setResizable(false);
        query.setDisable(true);
        Query.showAndWait();
        query.setDisable(false);
    }
    java.time.LocalDate bir;
    int id;
    String nam;
    String pho;
    String typ;

    @FXML
    void modifyMess(MouseEvent event) throws IOException {
        id= Integer.parseInt(ID.getText());
        bir=birthday.getValue();
        nam=name.getText();
        pho=phone.getText();
        typ = String.valueOf((RadioButton) type.getSelectedToggle());
        typ = typ.substring(typ.length() - 4,typ.length()-1); // Get the last three characters
        MassOrganizations mass=new MassOrganizations(id,nam,bir,typ,pho);
        System.out.println(mass.getBirthday());
        boolean re=userMethods.modifyMassOrganization(mass);
        System.out.println(re);
        Alert al = new Alert(Alert.AlertType.CONFIRMATION);
        if (re) {
            al.setHeaderText("ID为'" + mass.getId() + "'的社团信息已修改！");
        } else {
            al.setHeaderText("社团信息修改失败，请尝试重新进行操作！！！");
        }
        al.showAndWait();
        ID.setEditable(false);
        name.setEditable(false);
        birthday.setEditable(false);
        phone.setEditable(false);
        gongneng.setDisable(true);
        aihao.setDisable(true);
        yishu.setDisable(true);
        newTable();
    }

    @FXML
    void query(MouseEvent event) throws IOException {
        Stage Query = new Stage();
        FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("query.fxml"));
        Scene scene = new Scene((Parent)fxmlLoader.load(), 852.0, 490.0);
        Query.setTitle("查询社团信息");
        Query.setScene(scene);
        Query.setResizable(false);
        query.setDisable(true);
        Query.showAndWait();
        query.setDisable(false);
    }
    private void updateTableView(List<MassOrganizations> MassOrganizations) {
        modify.setDisable(true);
        this.table.getItems().addAll(MassOrganizations);
        this.tableId.setCellValueFactory(new PropertyValueFactory<>("Id"));
        this.tableName.setCellValueFactory(new PropertyValueFactory<>("Name"));
        this.tableBirthday.setCellValueFactory(new PropertyValueFactory<>("Birthday"));
        this.tableType.setCellValueFactory(new PropertyValueFactory<>("Type"));
        this.tablePhone.setCellValueFactory(new PropertyValueFactory<>("Phone"));
    }
    public void getPage(){
        totalPage = userMethods.getTotalPage();
        System.out.println(totalPage);
        Page.setPageCount(totalPage);
        // 设置事件监听器，用于在页索引更改时触发查询操作
        Page.currentPageIndexProperty().addListener((observable, oldValue, newValue) -> {
            page = newValue.intValue()+1;
            System.out.println("page:"+page);
            newTable();
        });
    }
    private void newTable(){
        try {
            table.getItems().clear();
            ObservableList<MassOrganizations> updatedData = userMethods.getMassOrganization(page);
            Platform.runLater(() -> updateTableView(updatedData));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
